package cn.gailvlun.gll.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.gailvlun.gll.R;



public class LetterIndexView extends LinearLayout implements View.OnTouchListener {

    char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    public LetterIndexView(Context context) {
        this(context, null);
    }

    public LetterIndexView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LetterIndexView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setOrientation(VERTICAL);
        for (char c : alphabet) {
            View.inflate(getContext(), R.layout.view_letter_index, this);
            ((TextView) getChildAt(getChildCount() - 1)).setText(String.valueOf(c));
        }
        setOnTouchListener(this);

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                handleTouch(event);
                return true;
            }
            case MotionEvent.ACTION_MOVE: {
                handleTouch(event);
                return true;
            }
            case MotionEvent.ACTION_UP: {
                handleTouch(event);
                return true;
            }
        }
        return false;
    }

    private char lastLetter;

    private void handleTouch(MotionEvent event) {
        int pos = 0;
        if (event.getY() > 0) {
            int realContent = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
            int realY = (int) (event.getY() - getPaddingTop());
            int unitY = realContent / alphabet.length;

            pos = realY / unitY;
        }
        pos = Math.min(pos, alphabet.length - 1);

        if (mOnTouchLetterListener != null && lastLetter != alphabet[pos]) {
            lastLetter = alphabet[pos];
            mOnTouchLetterListener.onTouchLetter(lastLetter);
        }
    }

    public interface OnTouchLetterListener {
        void onTouchLetter(char letter);
    }

    private OnTouchLetterListener mOnTouchLetterListener;

    public void setOnTouchLetterListener(OnTouchLetterListener onTouchLetterListener) {
        this.mOnTouchLetterListener = onTouchLetterListener;
    }
}
